<?php

if (!defined('IN_IA')) {
    exit('Access Denied');
}

class Bind_MxShopPage extends MobilePage
{
    protected $member;

    public function __construct()
    {
        global $_W, $_GPC;
        parent::__construct();
    }

    /*
     * ***用户绑定逻辑(只用于微信进入的用户)
     *
     * 1. GPC到手机号
     * 2. 查询此手机号是否存在用户
     * 2.1. 如果不存在 则注册用户并绑定
     * 2.2. 如果已存在 则判断同公众号是否绑定不同的微信userinfo
     * 2.2.1. 如果已绑定则判断是否微信用户；是则解绑用户，否则合并用户积分和余额
     */
    public function main()
    {
        global $_W, $_GPC;

        @session_start();

        //已注册跳到首页
//        if(!is_weixin() || empty($_W['openid']))
//        {
//            header('location:'.mobileUrl('index'));
//            exit();
//        }

        if($_W['ispost']){

            //验证令牌
            if(empty($_GPC['token']) || !$this->checkToken($_GPC['token'])){
                show_json(0, '参数有误');
            }

            $mobile = trim($_GPC['phone']);
            $verifycode = trim($_GPC['code']);

            $key = '__mx_shop_user_verifycodesession_' . $_W['uniacid'] . '_' . $mobile;
            if( !isset($_SESSION[$key]) ||  $_SESSION[$key]!==$verifycode || !isset($_SESSION['verifycodesendtime']) || $_SESSION['verifycodesendtime']+600<time())
            {
                show_json(0, '验证码错误或已过期');
            }

            $member = pdo_fetch('select * from ' . tablename('mx_shop_user') . ' where mobile=:mobile limit 1', array(':mobile' => $mobile));

            //未注册
            if(empty($member))
            {
                $id = $this->reg();

                $this->update($_W['openid'], array('uid'=>$id, 'isuser'=>1));

                unset($_SESSION[$key]);

                show_json(1, "bind success (0)");
            }

            //没有绑定过openid信息
            $userinfo = pdo_fetchall('select * from ' . tablename('mx_shop_userinfo') . ' where uid=:uid AND uniacid=:uniacid', array(':uid' => $member['id'], ':uniacid'=>$_W['uniacid']));
            if(!empty($userinfo))
            {
                foreach ($userinfo as $item)
                {
                    //如果是微信用户直接解绑-同公众号不同微信的info
                    if ($this->iswxm($item))
                    {
                        $this->update($item['openid'], array('uid' => 0, 'isuser' => 0));
                    }
                    else
                    {
                        //如果不是微信用户 则合并积分余额信息
                        if ($item['credit1'] > 0) {
                            m('userinfo')->setCredit($_W['openid'], 'credit1', abs($item['credit1']), '全网通会员数据合并增加积分 +' . $item['credit1']);
                        }
                        if ($item['credit2'] > 0) {
                            m('userinfo')->setCredit($_W['openid'], 'credit2', abs($item['credit2']), '全网通会员数据合并增加余额 +' . $item['credit2']);
                        }

                        //删除该info
                        pdo_delete('mx_shop_userinfo', array('id' => $item['id'], 'uniacid' => $item['uniacid']));
                    }
                }
            }

            //绑定注册用户
            $this->update($_W['openid'], array('uid'=>$member['id'], 'isuser'=>1));
            unset($_SESSION[$key]);
            show_json(1, "bind success (1)");

        }

        $sendtime = $_SESSION['verifycodesendtime'];
        if(empty($sendtime) || $sendtime+60<time())
        {
            $endtime = 0;
        }
        else
        {
            $endtime = 60 - (time() - $sendtime);
        }

        //获取令牌
        $token = $this->getToken();

        include $this->template();

    }

    //Reg注册用户
    protected function reg()
    {
        global $_W, $_GPC;

        //  获取数据并验证
        $mobile = trim($_GPC['phone']);
        $verifycode = trim($_GPC['code']);
        $pwd = trim($_GPC['pwd']);
        $pwd2 = trim($_GPC['pwd2']);
        if(empty($mobile) || !is_phone($mobile))
        {
            show_json(0, '请输入正确的手机号码');
        }
        if(empty($verifycode))
        {
            show_json(0, '请输入验证码');
        }
        if(empty($pwd) || empty($pwd2))
        {
            show_json(0, '请输入密码');
        }
        if($pwd != $pwd2)
        {
            show_json(0, '密码不一致');
        }

        //  获取/设置salt
        $salt = m('account')->getSalt();

        $data =array
        (
            'mobile'=>$mobile,
            'pwd'=>md5($pwd.$salt),
            'salt'=>$salt,
            'isstore'=>0,
            'createtime'=>time()
        );

        if(!empty($_W['openid']))
        {
            $userinfo = m('userinfo')->getUserInfo($_W['openid']);
            $data['realname']  = empty($userinfo['realname']) ? '' : $userinfo['realname'];
            $data['gender']  = empty($userinfo['gender']) ? 0 : $userinfo['gender'];
            $data['country']  = empty($userinfo['country']) ? '' : $userinfo['country'];
            $data['province']  = empty($userinfo['province']) ? '' : $userinfo['province'];
            $data['city']  = empty($userinfo['city']) ? '' : $userinfo['city'];
            $data['area']  = empty($userinfo['area']) ? '' : $userinfo['area'];
            $data['avatar']  = empty($userinfo['avatar']) ? '' : $userinfo['avatar'];
        }

        // 处理写入数据库
        pdo_insert('mx_shop_user', $data);
        $uid = pdo_insertid();

        //检测并绑定上级关系
        $this->checkParent($uid);

        return $uid;
    }

    //检测并绑定上级
    protected function checkParent($uid)
    {

        global $_W,$_GPC;

        if(empty($_GPC['mid']) || $_GPC['mid'] == $uid)
        {
            return false;
        }

        $sid = pdo_fetchcolumn('select id from '.tablename('mx_shop_user').' where id=:id limit 1',array(':id'=>intval($_GPC['mid'])));
        if(empty($sid))
        {
            return false;
        }

        $member = m('userinfo')->getUser($uid);
        $member = pdo_fetch('select id,parentid from '.tablename('mx_shop_user').' where id=:id limit 1',array(':id'=>intval($uid)));
        if(empty($member) || !empty($member['parentid']))
        {
            return false;
        }

        pdo_update('mx_shop_user', array('parentid' => $sid), array('id'=>$uid));
        return true;
    }

    /*
     * 更新userinfo表
     * @param string $openid 用户openid
     * @param array $arr 内容
     * @return bool
     */
    protected function update($openid='', $arr=array())
    {
        global $_W;
        if(empty($mid) || empty($arr) || !is_array($arr))
        {
            return false;
        }
        pdo_update('mx_shop_userinfo', $arr, array('openid'=>$openid, 'uniacid'=>$_W['uniacid']));
        return true;
    }

    /*
     * 判断用户是微信用户
     * @param array() $member 用户信息
     * @return bool
     */
    protected function iswxm($member=array())
    {
        if(empty($member) || !is_array($member))
        {
            return false;
        }
        if(strexists($member['openid'], 'sns_wx_') || strexists($member['openid'], 'sns_qq_') || strexists($member['openid'], 'wap_user_'))
        {
            return false;
        }
        return true;
    }
}
